package com.iseastar.guojiang.util;

import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;

import com.iseastar.guojiang.BeeApplication;

/**
 * Created by joker on 2018/5/22.
 */
public class MediaPlayerUtils {
    private static final String TAG = MediaPlayerUtils.class.getSimpleName();
    private static MediaPlayer mediaPlayer = null;

    private static MediaPlayerUtils mediaPlayerUtils = null;
    private PlayerMediaAsync playerMediaAsync = null;
    private boolean isLooping = true;

    public static MediaPlayerUtils getInstance() {
        if (mediaPlayerUtils == null) {
            synchronized (MediaPlayerUtils.class) {
                if (mediaPlayerUtils == null) {
                    mediaPlayerUtils = new MediaPlayerUtils();
                    mediaPlayer = new MediaPlayer();
                }
            }
        }
        return mediaPlayerUtils;
    }

    public MediaPlayer getMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        return mediaPlayer;
    }

    public synchronized void playerMusic(String fileName, boolean isLooping) {
        this.isLooping = isLooping;
        if (playerMediaAsync != null) {
            playerMediaAsync.cancel(true);
            playerMediaAsync = null;
        }
        playerMediaAsync = new PlayerMediaAsync();
        playerMediaAsync.execute(fileName);
    }

    class PlayerMediaAsync extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            try {
                getMediaPlayer();
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }
                AssetFileDescriptor fileDescriptor = BeeApplication.getContext().getAssets().openFd(params[0]);
                mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                        fileDescriptor.getStartOffset(),
                        fileDescriptor.getLength());
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//STREAM_ALARM
                mediaPlayer.prepare();
                mediaPlayer.setLooping(isLooping);
                mediaPlayer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public void destoryPlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (playerMediaAsync != null) {
            playerMediaAsync.cancel(true);
            playerMediaAsync = null;
        }
    }

}
